//
//  HelloClass.m
//  iOSCodeLearning
//
//  Created by TFAppleWork-Summer on 2018/4/3.
//  Copyright © 2018年 Ace. All rights reserved.
//

#import "HelloClass.h"
#import "RuntimeMethodHelper.h"

@interface HelloClass()
{
    RuntimeMethodHelper *_helper;
}
@end

@implementation HelloClass
- (instancetype)init
{
    self = [super init];
    if (self)
    {
        _helper = [RuntimeMethodHelper new];
    }
    return self;
}


+ (BOOL)resolveClassMethod:(SEL)sel
{
    NSString *selString = NSStringFromSelector(sel);
    if ([selString isEqualToString:@"hi"])
    {
        Class metaClass = objc_getMetaClass("HelloClass");
        class_addMethod(metaClass, @selector(hi), (IMP)functionForClassMethod, "v@:");
        return YES;
    }
    return [super resolveClassMethod:sel];
}
//+ (BOOL)resolveInstanceMethod:(SEL)sel
//{
//
//    NSString *selString = NSStringFromSelector(sel);
//    if ([selString isEqualToString:@"hello"])
//    {
//        class_addMethod(self, @selector(hello), (IMP)functionForMethod, "v@:");
//        return YES;
//    }
//    return [super resolveInstanceMethod:sel];
//}

void functionForMethod(id self, SEL _cmd)
{
    NSLog(@"Hello!");
}
Class functionForClassMethod(id self, SEL _cmd)
{
    NSLog(@"Hi!");
    return [HelloClass class];
}

#pragma mark - 备用接收者
//- (id)forwardingTargetForSelector:(SEL)aSelector{
//
//    NSString *selectorString = NSStringFromSelector(aSelector);
//    // 将消息交给_helper来处理? ?
//    if ([selectorString isEqualToString:@"hello"])
//    {
//    return _helper;
//    }
//    return [super forwardingTargetForSelector:aSelector];
//
//}

#pragma mark - 完整消息转发
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    NSLog(@"forwardInvocation");
    if ([RuntimeMethodHelper instancesRespondToSelector:anInvocation.selector]) {
        [anInvocation invokeWithTarget:_helper];
    }
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    NSMethodSignature *signature = [super methodSignatureForSelector:aSelector];
    if (!signature)
    {
        if ([RuntimeMethodHelper instancesRespondToSelector:aSelector])
        {
            signature = [RuntimeMethodHelper instanceMethodSignatureForSelector:aSelector];
        }
    }
    return signature;
}

@end
